<template>
	<view :style="[AppSkinVar]">
		<e-form labelPosition="left" :borderBottom="false" :labelStyle="{ color: '#333' }" labelWidth="232rpx"
			:model="formVal" :rules="rules" ref="form">
			<view class="form-box bg-white">
				<e-form-item class="form-item" :label="$t('user.收货人姓名')" prop="name">
					<e-input v-model="formVal.name" border="none"></e-input>
				</e-form-item>
				<e-form-item class="form-item" :label="$t('user.联系电话')" prop="phone">
					<e-input v-model="formVal.phone" type="number" border="none"></e-input>
				</e-form-item>
				<!-- 这里增加所在国家，国外会存在跨国上下班的情况 -->
				<e-form-item class="form-item" :label="$t('user.所在国家')" prop="nameExt"
					v-if="BIND_ADDRESS_TYPE === 'addressList'">
					<view class="e-flex-1 e-flex e-rela" @tap="pickerShowCountry = true">
						<view class="e-flex-1" :class="{ 'c-regular': !countryName }">
							{{ countryName || $t('common.请选择') }}
						</view>
						<image :src="$staticPath('layout/basics/right_arrow.png')" class="img-36"
							v-show="!formVal.nameExt"></image>
						<image src="../static/close.png" class="img-36" v-show="formVal.nameExt"
							@tap.stop="handleDelNameExt"></image>
					</view>
				</e-form-item>
				<e-form-item class="form-item" :label="$t('user.所在地区')" prop="nameExt"
					v-if="BIND_ADDRESS_TYPE === 'addressList'">
					<view class="e-flex-1 e-flex e-rela" @tap="pickerShow = true">
						<view class="e-flex-1" :class="{ 'c-regular': !formVal.nameExt }">
							{{ formVal.nameExt || $t('common.请选择') }}
						</view>
						<image :src="$staticPath('layout/basics/right_arrow.png')" class="img-36"
							v-show="!formVal.nameExt"></image>
						<image src="../static/close.png" class="img-36" v-show="formVal.nameExt"
							@tap.stop="handleDelNameExt"></image>
					</view>
				</e-form-item>
				<e-form-item class="form-item" :label="$t('user.所在地区')" prop="nameExt" v-else>
					<view class="e-flex-1 e-flex e-rela">
						<view class="e-flex-1" :class="{ 'c-regular': !userAddress.nameExt }" @tap="pickerShow = true">
							{{ formVal.nameExt || $t('user.addressSelectTips') }}
						</view>
						<!-- <image :src="$staticPath('layout/basics/right_arrow.png')" class="img-36"></image> -->

						<image src="/pages/user/static/position.png" class="img-40 e-m-l-30" @tap="jumpNearbyAddress">
						</image>
					</view>
				</e-form-item>
				<e-form-item class="form-item" :label="$t('user.详细地址')" prop="address">
					<e-textarea v-model="formVal.address" border="none"></e-textarea>
				</e-form-item>
			</view>
			<view class="e-m-t-20 bg-white e-p-30">
				<view class="e-m-b-10" style="border-bottom: 1px solid #ededed">
					<e-form-item class="form-item" :label="$t('user.label')" prop="label">
						<view class="e-flex-column" style="align-items: flex-start">
							<view class="e-flex e-m-b-20">
								<view :style="{
		background: label === item ? AppSkin.primary : '',
		color: label === item ? '#fff' : '',
		borderColor: label === item ? '' : ' #CCCCCC'
	}" class="label-box e-flex e-flex-xy-center e-m-r-20 e-font-24" v-for="(item, index) in labelList" :key="index"
									@tap="label = item">
									{{ item }}
								</view>
							</view>
							<view class="label-box e-flex e-flex-xy-center" style="border-color: #cccccc"
								@tap="handleAddLabel" v-if="!showAddLabel">+</view>
							<view class="" v-else>
								<view class="add-label-box e-p-l-20" v-if="isEdit">
									<e-input v-model="customLabel" border="none" focus
										:placeholder="$t('user.请输入标签名称')"></e-input>
									<view class="submit-label-btn"
										:style="{ background: customLabel ? AppSkin.primary : '' }"
										@tap="handleSubmitLabel">
										{{ $t('common.确定') }}
									</view>
								</view>
								<view class="edit-label-box" v-else
									:class="{ 'active-customlabel': customLabel === label }"
									:style="{ backgroundColor: customLabel === label ? AppSkin.primary : '' }">
									<view class="e-font-26 e-p-l-10 e-p-r-10" @tap="label = customLabel">
										{{ customLabel }}
									</view>
									<view class="submit-label-btn"
										:style="{ backgroundColor: customLabel === label ? AppSkin.primary : '' }"
										:class="{ 'active-customlabel': customLabel === label }" @tap="handleEditLabel">
										{{ $t('common.编辑') }}
									</view>
								</view>
							</view>
						</view>
					</e-form-item>
				</view>
				<view class="e-flex e-flex-between">
					<text>{{ $t('user.设为默认地址') }}</text>
					<radio :color="AppSkin.primary" value="1" :checked="formVal.isDefaul == 1"
						@tap="formVal.isDefaul = formVal.isDefaul ? 0 : 1" />
				</view>
			</view>
		</e-form>
		<view class="form-box">
			<view class="e-m-t-60">
				<e-button size="large" :disabled="!isOk" type="primary" shape="circle" :text="$t('common.保存')"
					@click="submit"></e-button>
			</view>

			<e-picker :cancelText="$t('common.取消')" :confirmText="$t('common.确认')" :show="pickerShowCountry"
				ref="uPicker" keyName="name" :columns="countryPickerList" :defaultIndex="defaultIndex"
				@cancel="pickerShowCountry = false" @confirm="confirm"></e-picker>
			<global-address ref="globalAddressRef" v-model="addrIds" :primary="AppSkin.primary" :show="pickerShow"
				:currentCountryCode="currentCountryCode" @textChange="handleTextChange"
				@close="pickerShow = false"></global-address>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed } from 'vue';
	import { useI18n, useCurrentInstance } from '@/common/hooks';
	import { useUser } from '@/common/stores';
	import { storeToRefs } from 'pinia';
	import { onLoad } from '@dcloudio/uni-app';
	import { postAddAddress,putEditAddress, getAddressInfo, splitAddr, getPhonePrefix} from '@/common/request/api';
	import type {AddressParams,CountryAreaItem} from '@/common/request/api';
	import { BIND_ADDRESS_TYPE } from '@/env';
	import { addressToLocation } from '@/common/utils/map/index';
	import type { GlobalAddressInstance } from '@/typings'

	const userI18 = useI18n('user');
	const ctx = useCurrentInstance();
	const props = defineProps<{
		type?: string;
		id?:string
	}>();
	const { userInfo } = storeToRefs(useUser());


	const editId = ref<string>();
	const pickerShow = ref(false);
	const pickerShowCountry = ref(false);
	const countryList = ref<CountryAreaItem[]>([]);
	const countryPickerList = ref<[string[]]>([[]]);
	const defaultIndex = ref<number[]>([]);
	const countryName = ref('');
	const currentCountryCode = ref('');
	const formVal = ref<Record<string, string | number>>({
		name: '',
		phone: '',
		nameExt: '',
		address: '',
		isDefaul: 0
	});
	const rules = ref({
		name: {
			type: 'string',
			required: true,
			message: userI18('请输入收货人姓名'),
			trigger: ['blur']
		},
		phone: {
			type: 'string',
			required: true,
			message: userI18('请输入联系电话'),
			trigger: ['blur']
		},
		nameExt: {
			type: 'string',
			required: true,
			message: userI18('请选择所在地区'),
			trigger: ['blur']
		},
		address: {
			type: 'string',
			required: true,
			message: userI18('请输入详细地址'),
			trigger: ['blur']
		}
	});
	const userAddress = ref<{
		latitudes?: number,
		longitudes?: number
	} & Record<string, any>>({});
	const addrIds = ref<string[]>([]);
	const labelList = ref([userI18('home'), userI18('company'), userI18('school')]);
	const label = ref('');
	const showAddLabel = ref(false);
	const customLabel = ref('');
	const isEdit = ref(true);
	const isOk = computed(() => {
		let value = false
		for (let i in formVal.value) {
			if (!formVal.value[i] && formVal.value[i] !== 0) {
				value = false;
				return value;
			} else {
				value = true;
			}
		}
		return value;
	});

	const globalAddressRef = ref<GlobalAddressInstance>()

	const confirm = (e: any) => {
		console.log(e, 'e...');
		pickerShowCountry.value = false;
		const val = e.indexs[0];
		currentCountryCode.value = countryList.value[val].countryArea;
		countryName.value = countryList.value[val].countryName;
		ctx.$nextTick(() => globalAddressRef.value?.init());
	};
	const handleTextChange = (val: string) => {
		formVal.value.nameExt = val;
		console.log(val, formVal.value, 'vall');
	};
	const handleDelNameExt = () => {
		addrIds.value = [];
		formVal.value.nameExt = '';
	};
	const handleEditLabel = () => {
		isEdit.value = true;
		label.value = customLabel.value;
	};
	const handleSubmitLabel = () => {
		isEdit.value = false;
		label.value = customLabel.value;
	};
	const handleAddLabel = () => {
		showAddLabel.value = true;
		label.value = '';
	};
	const init = (isGet = true) => {
		getPhonePrefix().then((res) => {
			if (res.code == 200) {
				countryList.value = res.data;
				const arr = countryList.value.map((item) => item.countryName);
				countryPickerList.value = [arr];
				if (currentCountryCode.value) {
					countryList.value.some((item, index) => {
						if (item.countryArea == currentCountryCode.value) {
							defaultIndex.value = [index];
							countryName.value = item.countryName;
							return true;
						}
					});
				} else {
					if (userInfo.value.countryArea) {
						countryList.value.some((item, index) => {
							if (item.countryArea === userInfo.value.countryArea) {
								defaultIndex.value = [index];
								currentCountryCode.value = item.countryArea;
								countryName.value = item.countryName;
								return true;
							}
						});
					} else {
						defaultIndex.value = [0];
						currentCountryCode.value = countryList.value[0].countryArea;
						countryName.value = countryList.value[0].countryName;
					}
				}

				ctx.$nextTick(() => {
					try {
						globalAddressRef.value?.init(isGet);
					} catch (e) {
						ctx.$nextTick(() => {
							globalAddressRef.value?.init(isGet);
						});
					}
				});
			}
		});
	};
	const getUserNearbyAddress = async (data: {
		vicinity: string,
		latitudes: number,
		longitudes: number
	}) => {
		const params = {
			address: data.vicinity,
			location: `${data.latitudes},${data.longitudes}`
		};
		splitAddr(params).then((res) => {
			if (res.code == 200) {
				userAddress.value = {
					...res.data,
					latitudes: data.latitudes,
					longitudes: data.longitudes
				};
				globalAddressRef.value?.init();
				addrIds.value = [];
				formVal.value.address = res.data.village;
				formVal.value.nameExt = res.data.nameExt;
				formVal.value.latitude = data.latitudes;
				formVal.value.longitude = data.longitudes;
			}
		});
	};

	const jumpNearbyAddress = () => {
		// #ifdef APP || HTML5 || PREVIEW 
		ctx.$goTo('/pages/user/receivingAddress/nearbyAddress', {}, {
			getUserNearbyAddress
		})
		// #endif
		// #ifdef MP
		uni.chooseLocation({
			success: function (res) {
				getUserNearbyAddress({
					vicinity: res.address,
					latitudes: res.latitude,
					longitudes: res.longitude
				})
			}
		});
		// #endif
		// #ifdef SUBSCRIPTION || PRIVATE
		wx.chooseLocation({
			success: function (res) {
				getUserNearbyAddress({
					vicinity: res.address,
					latitudes: res.latitude,
					longitudes: res.longitude
				})
			}
		});
		// #endif
	}
	const submit = async () => {
		if (!isOk.value) return;
		let formData = { ...formVal.value, id: editId.value, labelName: label.value } as AddressParams;
		let [proId, cityId, areaId, townId = '0'] = addrIds.value;
		formData['proId'] = proId;
		formData['cityId'] = cityId;
		formData['areaId'] = areaId;
		formData['townId'] = townId;
		if (proId) {
			const text = `${formVal.value.nameExt}${formVal.value.address}`;
			const _res = await addressToLocation(text);

			if (_res.longitude) {
				formData = {
					...formData,
					longitude: _res.longitude,
					latitude: _res.latitude
				};
			}
		}
		if (BIND_ADDRESS_TYPE !== 'addressList') {
			if (!formVal.value.address) {
				ctx.$toastApp(ctx.$t('user.addressSelectTips'));
				return;
			}
			formData = {
				...formData,
				longitude: userAddress.value.longitudes!,
				latitude: userAddress.value.latitudes!
			};
		}
		console.log(formData, 'form');
		formData.countryArea = currentCountryCode.value;
		const api = editId.value === null ? postAddAddress : putEditAddress
		api(formData).then((res) => {
			if (res.code == 200) {
				ctx.$toastApp(res.msg);
				setTimeout(() => {
					ctx.$back();
				}, 500);
			}
		});
	};

	onLoad(() => {
		if (props.type == '1') {
			uni.setNavigationBarTitle({
				title: ctx.$t('user.编辑地址')
			});
			editId.value = props.id;
			getAddressInfo(props.id!).then((res) => {
				if (res.code == 200) {
					let { name, phone, address, isDefaul, proId, cityId, areaId, townId } = res.data;
					currentCountryCode.value = res.data.countryArea;
					formVal.value = {
						name,
						phone,
						nameExt: res.data.nameExt,
						address,
						isDefaul
					};
					addrIds.value = [proId, cityId, areaId, townId];
					userAddress.value = {
						nameExt: formVal.value.nameExt,
						village: formVal.value.address,
						latitudes: res.data.latitude,
						longitudes: res.data.longitude
					};
					init(false);
					label.value = res.data.labelName;
					if (!labelList.value.includes(res.data.labelName) && res.data.labelName) {
						customLabel.value = res.data.labelName;
						showAddLabel.value = true;
						isEdit.value = false;
					}
				}
			});
		} else {
			init();
		}
	});
</script>
<style>
	page {
		padding: 20rpx 30rpx;
	}
</style>
<style lang="scss" scoped>
	.form-box {
		padding: 0 30rpx 0rpx 30rpx;

		.form-item {
			padding: 10rpx 0;
			box-shadow: 0px -1px 0px 0px #ededed;
		}
	}

	:deep(.e-form-item__body__left) {
		display: block !important;
	}

	:deep(.e-textarea) {
		padding: 0 !important;
	}

	.address-popup-mask {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		background-color: #fff;
		z-index: $z-index-normal;
	}

	.address-swiper {
		width: 100%;
		height: 800rpx;
		position: relative;

		.address-swiper-item {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;

			scroll-view {
				height: 800rpx;
			}
		}
	}

	.c-34 {
		color: #343434;
	}

	.label-box {
		width: 100rpx;
		height: 40rpx;
		border-radius: 4rpx;
		border: 1px solid;
	}

	.add-label-box {
		background-color: rgba(0, 0, 0, 0.05);
		height: 50rpx;
		border-radius: 25rpx;
		width: 350rpx;
		display: flex;

		.submit-label-btn {
			background-color: rgba(0, 0, 0, 0.1);
			border-radius: 0 25rpx 25rpx 0;
			padding: 0 10rpx;
			font-size: 26rpx;
			line-height: 50rpx;
			color: #fff;
		}
	}

	.edit-label-box {
		height: 50rpx;
		line-height: 50rpx;
		border-radius: 25rpx;
		display: flex;
		border: 1px solid rgba(0, 0, 0, 0.05);

		.submit-label-btn {
			background-color: rgba(0, 0, 0, 0.8);
			border-radius: 0 25rpx 25rpx 0;
			padding: 0 10rpx;
			font-size: 26rpx;
			color: #fff;
			border-left: 1px solid #fff;
		}
	}

	.active-customlabel {
		color: #fff !important;
	}

	@font-face {
		font-family: 'iconfont';
		/* Project id 3886169 */
		src: url('../font/iconfont.woff2?t=1675844873137') format('woff2'), url('../font/iconfont.woff?t=1675844873137') format('woff'),
			url('../font/iconfont.ttf?t=1675844873137') format('truetype');
	}

	.iconfont {
		font-family: 'iconfont' !important;
		font-size: 16px;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
	}

	.icon-position02:before {
		content: '\e6c4';
	}
</style>
